import {delay} from 'redux-saga';
import qs from 'querystring';
import {
  takeEvery,
  put,
  call,
  all,
  select,
  fork,
  take
} from 'redux-saga/effects';
import {REGISTER_REQUEST, REGISTER_SUCCESS, REGISTER_FAILURE} from 'actions';
import ajax from 'ajax';

export default function * watchRegister() {
  while (true) {
    const payload = yield take(REGISTER_REQUEST);
    try {
      const response = yield call(ajax.post, 'users', qs.stringify({username: payload.username, password: payload.password, email: payload.email}));
      if (response.status === 200 && response.data && response.data !== '') {
        yield put({type: REGISTER_SUCCESS, data: response.data});
      } else {
        yield put({type: REGISTER_FAILURE, error: '注册失败。服务器错误！'});
      }
    } catch (error) {
      yield put({type: REGISTER_FAILURE, error: '用户已存在'});
    }
  }
}
